package com.peng.safety.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar

object SnackUtil {

    private var bar: Snackbar? = null
    private var currentActivity: Activity? = null
    val activities: ArrayList<Activity> = ArrayList()

    fun init(app: Application) {
        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {
            }

            override fun onActivityResumed(activity: Activity?) {
            }

            override fun onActivityStarted(activity: Activity?) {
            }

            override fun onActivityDestroyed(activity: Activity?) {
                activity?.let { activities.remove(it) }
            }

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
            }

            override fun onActivityStopped(activity: Activity?) {
            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
                activity?.let { activities.add(it) }
            }

        })
    }

    fun show(msg: String?, succ: Boolean? = null) {

        if (activities.size > 0 && activities[activities.size - 1] != currentActivity) {
            currentActivity = activities[activities.size - 1]
            bar = Snackbar.make(
                activities[activities.size - 1].window.decorView, msg
                    ?: "", Snackbar.LENGTH_SHORT
            )
        } else {
            bar?.setText(msg ?: "")
        }

        currentActivity?.let { activity ->
            bar?.apply { view.setBackgroundColor(activity.resources.getColor(if (succ == null) android.R.color.black else if (succ) android.R.color.holo_green_dark else android.R.color.holo_red_dark)) }
        }

        bar?.show()
    }
}